﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Jayden.Dll.Core.IO
{
	public class BigEndianWriter : IDisposable
	{
		private BinaryWriter m_Writer;
		private bool m_DisposeInnerWriter;

		public BigEndianWriter(Stream stream)
		{
			m_Writer = new BinaryWriter(stream);
			m_DisposeInnerWriter = true;
		}

		public BigEndianWriter(BinaryWriter writer)
		{
			m_Writer = writer;
			m_DisposeInnerWriter = false;
		}

		public BinaryWriter InnerWriter { get { return m_Writer; } }

		public void Write(short value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			WriteBigEndianBytes(bytes);
		}

		public void Write(int value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			WriteBigEndianBytes(bytes);
		}

		public void Write(long value)
		{
			byte[] bytes = BitConverter.GetBytes(value);
			WriteBigEndianBytes(bytes);
		}

		protected void WriteBigEndianBytes(byte[] bytes)
		{
			for (int c = bytes.Length - 1; c >= 0; c--)
				m_Writer.Write(bytes[c]);
		}

		public void Dispose()
		{
			if (m_DisposeInnerWriter && m_Writer != null)
				m_Writer.Dispose();
			m_Writer = null;
		}
	}
}
